import { Body, Controller, Get, HttpException, HttpStatus, Post, Req, SetMetadata } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import { JwtNeed } from '@/common/decorator'
import { SmsService } from '@/modules/sms/sms.service'
import { ExpressDto, LoginPlayerUserDto, SendMessageDto } from './dto/player-user.dto'
import { PlayerUserService } from './player-user.service'

export const SkipFormat = () => SetMetadata('smsSkipFormat', true)

@ApiTags('官网/二期/用户')
@Controller('web/play_user')
export class PlayerUserController {
  constructor(private readonly playerService: PlayerUserService, private readonly smsService: SmsService) {}

  /**
   * 用户登录(获取token)
   */
  @Post('login')
  @SkipFormat()
  async login(@Body() data: LoginPlayerUserDto) {
    const response = await this.playerService.loginOrRegister(data)
    return response
  }

  /**
   * 发送验证码
   */
  @Post('send_message')
  @SkipFormat()
  async sendMessage(@Body() data: SendMessageDto) {
    const response = await this.smsService.sendCodeByPhone(data)
    return response
  }

  /**
   * 当前用户信息
   */
  @Get('info')
  @JwtNeed()
  async getInfo(@Req() req: Request) {
    const response = await this.playerService.findAndUpdateUserInfo(req.user.uid)
    return response
  }

  /**
   * 当前用户地址
   */
  @Get('express')
  @JwtNeed()
  async getExpress(@Req() req: Request) {
    return await this.playerService.findUserExpress(req.user.uid)
  }

  /**
   * 更新用户收货地址
   */
  @Post('express_info')
  @JwtNeed()
  async addExpressInfo(@Req() req: Request, @Body() body: ExpressDto) {
    if (!req.user?.uid) {
      throw new HttpException('请先登录', HttpStatus.UNAUTHORIZED)
    }

    const player = await this.playerService.findOne({ where: { uid: req.user.uid } })
    if (!player) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST)
    }

    this.playerService.update({ uid: req.user.uid }, { expressInfo: body })
  }
}
